import requests
import argparse
import re
from urllib3.exceptions import InsecureRequestWarning

# 禁用 SSL 验证警告（可选）
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)


def download_file(url, filename):
    """下载文件（忽略证书验证）"""
    with requests.get(url, stream=True, verify=False) as r:  # 添加 verify=False
        r.raise_for_status()
        with open(filename, "wb") as f:
            for chunk in r.iter_content(chunk_size=8192):
                f.write(chunk)


def fetch_release_assets(owner, repo, tag, keyword):
    """获取资源（忽略证书验证）"""
    api_url = f"https://api.github.com/repos/{owner}/{repo}/releases/tags/{tag}"
    response = requests.get(api_url, verify=False)  # 添加 verify=False
    response.raise_for_status()

    assets = response.json().get("assets", [])
    pattern = re.compile(re.escape(keyword), re.IGNORECASE)

    return [
        (asset["name"], asset["browser_download_url"])
        for asset in assets
        if pattern.search(asset["name"])
    ]


def main():
    parser = argparse.ArgumentParser(
        description="GitHub Release 文件下载工具",
        formatter_class=argparse.RawTextHelpFormatter,
    )
    parser.add_argument("--tag", required=True, help="Release 标签（如 20250311）")
    parser.add_argument(
        "--keyword",
        required=True,
        help="文件名包含的关键字（如 x86_64-pc-windows-msvc-install_only_stripped）",
    )
    parser.add_argument(
        "--owner", default="astral-sh", help="GitHub 仓库拥有者（默认：astral-sh）"
    )
    parser.add_argument(
        "--repo",
        default="python-build-standalone",
        help="GitHub 仓库名称（默认：python-build-standalone）",
    )

    args = parser.parse_args()

    try:
        print(f"正在获取 {args.tag} 版本的资源列表...")
        matched_files = fetch_release_assets(
            args.owner, args.repo, args.tag, args.keyword
        )

        if not matched_files:
            print(f"未找到包含 '{args.keyword}' 的文件")
            return

        print(f"找到 {len(matched_files)} 个匹配文件：")
        for name, _ in matched_files:
            print(f"  - {name}")

        print("\n开始下载：")
        for filename, url in matched_files:
            print(f"正在下载 {filename}...", end="", flush=True)
            download_file(url, filename)
            print(" ✅")

    except requests.exceptions.HTTPError as e:
        print(f"\n错误：{e.response.status_code} - {e.response.reason}")
        if e.response.status_code == 404:
            print("请检查以下内容：")
            print(f"1. 标签 {args.tag} 是否存在？")
            print(f"2. 仓库 {args.owner}/{args.repo} 是否正确？")
    except Exception as e:
        print(f"\n发生错误：{str(e)}")


if __name__ == "__main__":
    main()


# 执行
# python .\down2.py --tag 20250311 --keyword x86_64-pc-windows-msvc-install_only_stripped -o my_urls.txt
